<template>
  <div style="width: 100%">
    <div class="byted-weektime" @mousedown="dian" @mousemove="yi" @mouseup="li">
      <div class="calendar">
        <ul class="calendar-list">
          <li class="calendar-head">
            <div v-for="i in 24" :key="i" style="width: 4.166%">
              {{ i - 1 < 10 ? '0' + (i - 1) : i - 1 }} </div>
          </li>
          <li class="calendar-row">
            <div @mousedown.prevent="handleMouseDown(i, 0)" @mouseup.prevent="handleMouseUp(i)"
              class="calendar-atom-time" :class="item.class" v-for="(item, i) in rowUnit[0]" :key="i"></div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, defineEmits, watch } from 'vue'

// 编辑数据
const editData: any = ref([])
const props = defineProps(['holidayData', 'tabKey'])
const emit = defineEmits<{
  (e: 'updateTemplateData', val: { timePeriods: string[] }): void
}>()

const rowUnit = ref<Array<Array<{ class: string | null; timeData: number }>>>(
  [],
)
const timeContent = ref<Array<{ arr: number[] }>>([])
const timeSection = ref<Array<Array<number[]>>>([])
const timeStr = ref<string[]>([])
let beginDay = ref<number>(0)
let beginTime = ref<number>(0)
let downEvent = ref<boolean>(false)
// const kuangObj = ref<{
//   width: number
//   height: number
//   top: number
//   left: number
//   bottom: number
//   right: number
//   oldLeft: number
//   oldTop: number
//   flag: boolean
// }>({
//   width: 0,
//   height: 0,
//   top: 0,
//   left: 0,
//   bottom: 0,
//   right: 0,
//   oldLeft: 0,
//   oldTop: 0,
//   flag: false,
// })
let py = ref<string>('')
let px = ref<string>('')
let back = ref<string>('#31676f')
let h = ref<string>('')
let w = ref<string>('')
let top = ref<string>('')
let left = ref<string>('')
let len = ref<number>(0)

onMounted(() => {
  init()
})

const init = () => {
  for (let i = 0; i < 7; i++) {
    let arr: { class: string | null; timeData: number }[] = []
    for (let j = 0; j < 48; j++) {
      arr.push({ class: null, timeData: j })
    }
    rowUnit.value.push(arr)
    timeContent.value.push({ arr: [] })
    timeSection.value.push([])
    timeStr.value.push('')
  }

  const templateData = generateTemplateData()
  emit('updateTemplateData', templateData)
}

const handleMouseDown = (i: number, day: number) => {
  downEvent.value = true
  beginDay.value = day
  beginTime.value = i
}

const dian = (event: MouseEvent) => {
  px.value = event.pageX.toString()
  py.value = event.pageY.toString()
}

const yi = (event: MouseEvent) => {
  if (px.value === '' || py.value === '') {
    return
  }
  let px1 = parseInt(px.value)
  let px2 = parseInt(py.value)
  left.value = event.pageX.toString()
  top.value = event.pageY.toString()
  h.value = (parseInt(top.value) - px2).toString()
  w.value = (parseInt(left.value) - px1).toString()
  let hc = -parseInt(h.value)
  let wc = -parseInt(w.value)
  len.value = 1
  back.value = '#31676f'
  if (parseInt(h.value) < 0 && parseInt(w.value) >= 0) {
    h.value = hc.toString()
    left.value = px1.toString()
  } else if (parseInt(h.value) >= 0 && parseInt(w.value) < 0) {
    w.value = wc.toString()
    top.value = px2.toString()
  } else if (parseInt(h.value) < 0 && parseInt(w.value) < 0) {
    h.value = hc.toString()
    w.value = wc.toString()
  } else {
    left.value = px.value
    top.value = py.value
  }
  if (parseInt(w.value) < 0) {
    w.value = (0 - parseInt(w.value)).toString()
  }
  if (parseInt(h.value) < 0) {
    h.value = (0 - parseInt(h.value)).toString()
  }
}

const li = () => {
  px.value = ''
  py.value = ''
  h.value = ''
  w.value = ''
  top.value = ''
  left.value = ''
  len.value = 0
  back.value = ''
}

const handleMouseUp = (i: number) => {
  let begin = beginTime.value
  let start = begin <= i ? begin : i
  let length = Math.abs(begin - i)
  let end = start + length

  const isAdd = (): boolean => {
    for (let y = start; y < end + 1; y++) {
      if (rowUnit.value[beginDay.value][y].class === null) return true
    }
    return false
  }

  if (downEvent.value) {
    if (isAdd()) {
      for (let y = start; y < end + 1; y++) {
        if (rowUnit.value[beginDay.value][y].class === null) {
          rowUnit.value[beginDay.value][y].class = 'ui-selected'
          timeContent.value[beginDay.value].arr.push(
            rowUnit.value[beginDay.value][y].timeData,
          )
        }
      }
    } else {
      for (let y = start; y < end + 1; y++) {
        if (rowUnit.value[beginDay.value][y].class === 'ui-selected') {
          rowUnit.value[beginDay.value][y].class = null
          let c = rowUnit.value[beginDay.value][y].timeData
          let index = timeContent.value[beginDay.value].arr.indexOf(c)
          if (index > -1) {
            timeContent.value[beginDay.value].arr.splice(index, 1)
          }
        }
      }
    }
    filterTime(beginDay.value, beginDay.value)
    const templateData = generateTemplateData()
    emit('updateTemplateData', templateData)
  }
  downEvent.value = false
}

const toStr = (num: number): string => {
  if (Number.isInteger(num)) {
    let str = num < 10 ? '0' + num : num.toString()
    return str + ':00'
  } else {
    let str =
      Math.floor(num) < 10 ? '0' + Math.floor(num) : Math.floor(num).toString()
    return str + ':30'
  }
}

const filterTime = (start: number, end: number) => {
  const sortCut = (arr: number[]): number[][] => {
    let result: number[][] = []
    arr.forEach((v, i) => {
      let temp = result[result.length - 1]
      if (!i) {
        result.push([v])
      } else if (v % 1 === 0 && v - temp[temp.length - 1] === 1) {
        temp.push(v)
      } else {
        result.push([v])
      }
    })
    return result
  }

  const timeToStr = (arr: number[][]): string => {
    let str = ''
    arr.forEach((arr, index) => {
      let str1 = ''
      if (index === 0) {
        str1 = toStr(arr[0]) + '~' + toStr(arr[1])
      } else {
        str1 = ' , ' + toStr(arr[0]) + '~' + toStr(arr[1])
      }
      str += str1
    })
    return str
  }

  for (let i = start; i < end + 1; i++) {
    let arr1 = sortCut(timeContent.value[i].arr.sort((a, b) => a - b))
    let arr2: number[][] = []
    arr1.forEach((arr) => {
      let arr3: number[] = []
      arr3.push(arr[0] / 2)
      arr3.push(arr[arr.length - 1] / 2 + 0.5)
      arr2.push(arr3)
    })
    timeStr.value[i] = timeToStr(arr2)
    timeSection.value[i] = arr2

    const templateData = generateTemplateData()
    emit('updateTemplateData', templateData)
  }
}

const generateTemplateData = (): {
  timePeriods: string[]
} => {
  const timePeriods: string[] = []

  if (timeSection.value[0].length > 0) {
    timeSection.value[0].forEach((segment) => {
      const startTime = toStr(segment[0])
      const endTime = toStr(segment[1])
      timePeriods.push(`${startTime}-${endTime}`)
    })
  }

  return { timePeriods }
}

const renderTimePeriods = () => {

  init()
  if (editData.value.length > 0) {
    editData.value.forEach((data: any, dataIndex: number) => {
      const timePlanList = data.timePlanList // 提取 timePlanList
      // 初始化 timeContent.value[dataIndex].arr，如果它尚未初始化
      if (!timeContent.value[dataIndex]) {
        timeContent.value[dataIndex] = { arr: [] } // 确保 arr 是一个空数组
      } else if (!timeContent.value[dataIndex].arr) {
        timeContent.value[dataIndex].arr = [] // 确保 arr 是一个空数组
      }
      timePlanList.forEach((plan: any) => {
        const [startHour, startMinute] = plan.startTime.split(':').map(Number)
        const [endHour, endMinute] = plan.endTime.split(':').map(Number)
        const startIndex = startHour * 2 + (startMinute === 30 ? 1 : 0)
        const endIndex = endHour * 2 + (endMinute === 30 ? 1 : 0)

        // 确保 rowUnit.value 和 timeContent.value 存在
        if (rowUnit.value && timeContent.value) {
          // 确保 rowUnit.value[dataIndex] 存在
          if (rowUnit.value[dataIndex]) {

            for (let i = startIndex; i <= endIndex; i++) {
              // 确保 rowUnit.value[dataIndex][i] 存在
              if (rowUnit.value[dataIndex][i]) {
                rowUnit.value[dataIndex][i].class = 'ui-selected'
                timeContent.value[dataIndex].arr.push(i) // 确保 arr 已经初始化
              } else {
                console.warn(`rowUnit.value[${dataIndex}][${i}] is undefined`)
              }
            }
          } else {
            console.warn(`rowUnit.value[${dataIndex}] is undefined`)
          }
        } else {
          console.warn('rowUnit.value or timeContent.value is undefined')
        }
      })
    })

    // 更新时间段
    filterTime(0, 0)
  }
}
watch(
  () => props.holidayData,
  (newHolidayData) => {
    if (props.tabKey == 'edit' && newHolidayData) {
      // 确保 editData.value 是一个数组
      editData.value = Array.isArray(newHolidayData)
        ? newHolidayData
        : [newHolidayData]
      if (editData.value[0].timePlanList) {
        if (editData.value[0].timePlanList.length > 0) {
          renderTimePeriods()
        }
      }
    }
  },
  { immediate: true },
)
</script>
<style lang="scss" scoped>
.byted-weektime .calendar {
  width: 100%;
  -webkit-user-select: none;
  position: relative;
  display: inline-block;
}

#tableBody {
  background-color: #f8f8f8;
}

.byted-weektime .calendar .calendar-list {
  width: 100%;
  border-collapse: collapse;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.byted-weektime .calendar .calendar-list .calendar-head {
  display: flex;
  justify-content: space-between;
  color: #999;
  line-height: 2.4em;
  text-align: center;
}

.byted-weektime .calendar .calendar-list .calendar-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  background-color: #f8f8f8;
  font-size: 12px;
  text-align: center;
  line-height: 1.8em;
  -webkit-transition: background 200ms ease;
  -moz-transition: background 200ms ease;
  -ms-transition: background 200ms ease;
  transition: background 200ms ease;
}

.byted-weektime .calendar .calendar-list .calendar-row .calendar-atom-time {
  width: 4.166%;
  height: 20px;
  box-sizing: border-box;
  border-right: 1px solid #fff;
}

.byted-weektime .calendar .calendar-list .calendar-row .calendar-atom-time:hover {
  background-color: #459FFF;
}

.byted-weektime .calendar .calendar-list .calendar-row .ui-selected {
  background-color: #459FFF;
  border: none;
}

.byted-weektime .calendar .calendar-list .calendar-row .ui-selected:hover {
  background-color: #459FFF;
}

#kuang {
  position: absolute;
  background-color: blue;
  opacity: 0.3;
}
</style>